﻿namespace BadHabit.Factory.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;

    /// <summary>
    /// Interaction logic for ArtifactListBox.xaml
    /// </summary>
    public partial class ArtifactListBox : ListBox
    {
        public string BacklogItemUId { get; set; }

        internal static readonly DependencyProperty TaskUIdProperty = DependencyProperty.Register("TaskUId", typeof(string), typeof(ArtifactListBox), null);

        public string TaskUId
        {
            get
            {
                return (string)GetValue(TaskUIdProperty);
            }

            set
            {
                SetValue(TaskUIdProperty, value);
            }
        }

        internal static readonly DependencyProperty ProjectProperty = DependencyProperty.Register("Project", typeof(Data.ProjectDataSet.ProjectRow), typeof(ArtifactListBox), null);

        public Data.ProjectDataSet.ProjectRow Project
        {
            get
            {
                return (Data.ProjectDataSet.ProjectRow)GetValue(ProjectProperty);
            }

            set
            {
                SetValue(ProjectProperty, value);
            }
        }

        public Predicate<Object> IsInFilter
        {
            get;
            set;
        }

        public ArtifactListBox()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Load the artifacts
        /// </summary>        
        public void LoadArtifacts()
        {
            Data.TaskDataSet tail = new BadHabit.Factory.Data.TaskDataSet();

            if (Project == null)
            {
                return;
            }

            try
            {
                if (BacklogItemUId == null)
                {
                    tail.Merge(Client.Service.RetriveArtifactsByProjectUId(Project.ProjectUId, Project.Category));
                }
                else
                {
                    tail.Merge(Client.Service.RetriveArtifactsByBacklogItemUId(BacklogItemUId, Project.Category));
                }
            }
            catch (Exception ex)
            {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_READ_ARTIFACTS);
            }

            System.Windows.Data.ListCollectionView artifactView = new System.Windows.Data.ListCollectionView(tail.TaskTail.DefaultView);
            ItemsSource = artifactView;

            artifactView.GroupDescriptions.Add(new PropertyGroupDescription("ArtifactGroup"));
            artifactView.SortDescriptions.Add(new System.ComponentModel.SortDescription("ActivityOrder", System.ComponentModel.ListSortDirection.Ascending));
            artifactView.SortDescriptions.Add(new System.ComponentModel.SortDescription("ArtifactName", System.ComponentModel.ListSortDirection.Ascending));

            if (IsInFilter != null)
            {
                artifactView.Filter = IsInFilter;
            }
            else
            {
                artifactView.Filter = IsInFilterTaskUId;
            }

            SelectedItem = null;
        }

        protected void HandleDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(((ListBoxItem)sender).DataContext);
            if (tail == null)
            {
                return;
            }

            Helper.OpenOSWindow(MountArtifactURL(tail));
        }

        private string MountArtifactURL(Data.TaskDataSet.TaskTailRow tail)
        {
            if (!tail.IsSourceControled)
            {
                return tail.ArtifactPath;
            }

            string url = Client.SourceControlViewUrl.ToLower();
            url = url.Replace("$repositoryurl$", tail.RepositoryUrl);
            url = url.Replace("$artifactrevision$", tail.ArtifactRevision.ToString());
            url = url.Replace("$artifactpath$", tail.ArtifactPath);

            return url;
        }

        private void OpenMenuItemClick(object sender, RoutedEventArgs e)
        {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(this.SelectedItem);
            if (tail == null)
            {
                return;
            }

            Helper.OpenOSWindow(MountArtifactURL(tail));
        }

        private void RemoveTailMenuItemClick(object sender, RoutedEventArgs e)
        {
            Data.TaskDataSet.TaskTailRow tail = Helper.GetRowFromRowView<Data.TaskDataSet.TaskTailRow>(this.SelectedItem);

            if (tail == null)
            {
                return;
            }

            try
            {
                Client.Service.RemoveTaskTailFromBacklogItem(tail.ArtifactPath, BacklogItemUId);
            }
            catch (Exception ex)
            {
                Views.Error.ShowError(ex, global::BadHabit.Factory.Windows.Properties.Resources.COULD_NOT_REMOVE_TAIL);
                return;
            }

            System.Windows.Data.ListCollectionView artifactView = this.ItemsSource as System.Windows.Data.ListCollectionView;
            artifactView.Remove(artifactView.CurrentItem);
        }

        private bool IsInFilterTaskUId(object obj)
        {
            System.Data.DataRowView tail = obj as System.Data.DataRowView;
            if (tail == null)
            {
                return false;
            }

            if (TaskUId != null &&
                !tail["TaskUId"].ToString().Equals(TaskUId))
            {
                return false;
            }

            return true;
        }

        private void listBox_Drop(object sender, DragEventArgs e)
        {
            IDataObject o = e.Data;
            string[] fileName = o.GetData("FileNameW") as string[];
            if (fileName == null)
            {
                return;
            }

            TaskViewerBase.AddTaskMaterial(TaskUId, Project.ProjectDocBase, fileName, false);

            LoadArtifacts();
        }
    }
}
